// 默认服务器地址
const DEFAULT_BASE_URL = 'http://10.43.122.136:8080/api/';
// const DEFAULT_BASE_URL = 'http://192.168.3.6:1010/api/';

// 获取应用版本号
const getAppVersion = (): string => {
  // 根据平台返回不同格式的版本号
  //版本号设置
  if (Platform.OS === 'ios') {
    return 'ios_1.0.7';
  } else if (Platform.OS === 'android') {
    return 'android_1.0.7';
  } else {
    return '1.0.7';
  }
};

import AsyncStorage from '@react-native-async-storage/async-storage';
import { Platform } from 'react-native';

let token: string | null = null;
let baseUrl: string | null = null;

// 获取服务器地址
export const getBaseUrl = async (): Promise<string> => {
  if (baseUrl) return baseUrl;
  const storedUrl = await AsyncStorage.getItem('baseUrl');
  baseUrl = storedUrl || DEFAULT_BASE_URL;
  return baseUrl;
};

// 设置服务器地址
export const setBaseUrl = async (url: string) => {
  // 确保URL格式正确
  let formattedUrl = url.trim();
  if (!formattedUrl.endsWith('/')) {
    formattedUrl += '/';
  }
  if (!formattedUrl.endsWith('api/')) {
    formattedUrl += 'api/';
  }

  baseUrl = formattedUrl;
  await AsyncStorage.setItem('baseUrl', formattedUrl);
  console.log('服务器地址已更新为:', formattedUrl);
};

export const setToken = async (t: string) => {
  token = t;
  await AsyncStorage.setItem('token', t);
};

export const getToken = async () => {
  if (token) return token;
  token = await AsyncStorage.getItem('token');
  return token;
};

export async function request(path: string, options: RequestInit = {}) {
  const currentBaseUrl = await getBaseUrl();
  const url = currentBaseUrl + path.replace(/^\//, '');
  const t = await getToken();

  // 自动添加版本号到请求头
  const headers = {
    'Content-Type': 'application/json',
    'version': getAppVersion(),
    ...(options.headers || {}),
    ...(t ? { token: t } : {}),
  };

  console.log('请求URL:', url);
  console.log('请求headers:', headers);
  const res = await fetch(url, { ...options, headers });
  const data = await res.json();
  if (!res.ok) throw new Error(data.msg || '网络请求失败');
  return data;
} 